import { fileURLToPath } from 'url'
import path, { dirname } from 'path'
import fs from 'fs'

// 导入文件夹（批量导入文件）
export const importDir = async (dir = '', filterCurr = true) => {
  const rootPath = process.cwd() // 根路径
  const __filename = fileURLToPath(import.meta.url) // 当前文件路径
  const __dirname = dirname(__filename) // 当前文件夹路径
  const currFilename = __filename.replace(`${__dirname}/`, '') // 当前文件名

  const targetPath = dir ? `${rootPath}/${dir}` : __dirname
  let routes = fs.readdirSync(targetPath).filter(_ => _.includes('.')) // 过滤非文件
  routes = filterCurr ? routes.filter(_ => _ !== currFilename) : routes

  let modules = {}
  for (const name of routes) {
    modules[name] = (await import(`${targetPath}/${name}`)).default
  }

  return modules
}

// 深度导入文件夹中所有文件（index文件除外）
export async function deepImport(dir) {
  const rootPath = process.cwd() // 根路径
  const __filename = fileURLToPath(import.meta.url) // 当前文件路径
  const __dirname = dirname(__filename) // 当前文件夹路径
  // const currFilename = __filename.replace(`${__dirname}/`, '') // 当前文件名
  const targetDir = dir ? `${rootPath}/${dir}` : __dirname

  let modules = {}

  const loopFile = async (dir, pDirname = '') => {
    const files = fs.readdirSync(dir)

    for (const file of files) {
      if (!file.includes('index')) {
        const fullPath = path.join(dir, file)
        const stat = fs.lstatSync(fullPath)

        const joinDir = pDirname ? `${pDirname}/${file}` : file // 拼接文件夹
        if (stat.isDirectory()) {
          // 文件夹
          await loopFile(fullPath, joinDir)
        } else {
          modules[joinDir] = (await import(fullPath)).default
        }
      }
    }
  }

  await loopFile(targetDir)

  return modules
}

// 去除空属性
export function clean(obj) {
  for (var propName in obj) {
    if (obj[propName] === null || obj[propName] === undefined || obj[propName] === '') {
      delete obj[propName]
    }
  }
  return obj
}

// 首字母大写
export function titleCase(str) {
  return str.replace(/( |^)[a-z]/g, L => L.toUpperCase())
}

// 下划线 -> 驼峰(可自定义符号 默认下划线)
export function camelCase(str, separator = '_') {
  const reg = new RegExp(`${separator}[a-z]`, 'gim')
  return str.replace(reg, str1 => str1.substr(-1).toUpperCase())
}

// 驼峰 -> 下划线(可自定义符号 默认下划线)
export function snakeCase(str, separator = '_') {
  return str.replace(/([A-Z])/g, `${separator}$1`).toLowerCase()
}
